package com.gotrade.demo.server;

import com.gotrade.demo.protocol.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;

import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

/**
 * @author jason.tang
 * @create 2018-12-06 11:34
 * @description
 */

@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        // 解码
        Packet packet = PacketCodeC.INSTANCE.decode(byteBuf);

        if (packet instanceof LoginRequestPacket) {
            // 登录流程
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;

            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());

            if (valid(loginRequestPacket)) {
                loginResponsePacket.setSuccess(true);
                loginResponsePacket.setReason("帐号密码校验正确");
            } else {
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setReason("帐号密码校验失败");
            }

            // 登录响应
            ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
            ctx.channel().writeAndFlush(responseByteBuf);
        } else if (packet instanceof MessageRequestPacket) {
            // 客户端发来的消息
            MessageRequestPacket messageRequestPacket = (MessageRequestPacket) packet;
            System.out.println("Client：" + messageRequestPacket.getMessage());
            
            MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
            messageResponsePacket.setMessage("我是Server，倾听您的表达......当前时间是：" + new Date());
            ByteBuf msgResponseByteBuf= PacketCodeC.INSTANCE.encode(ctx.alloc(), messageResponsePacket);

            ctx.channel().writeAndFlush(msgResponseByteBuf);
        }

    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return Objects.equals(loginRequestPacket.getPassword(), "root") && loginRequestPacket.getVersion() == ((byte) 1);
    }
}